/*
 * @(#)$Id: codetemplate_xbird.xml 943 2006-09-13 07:03:37Z yui $
 * 
 * Copyright 2006-2008 Makoto YUI
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 * 
 * Contributors: Makoto YUI - initial implementation
 */
package jacky.lanlan.song.io;

import java.io.IOException;
import java.net.*;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * 
 * @author Makoto YUI (yuin405+xbird@gmail.com)
 */
public abstract class NetUtils {

	public static InetAddress getLocalHost() {
		try {
			return InetAddress.getLocalHost();
		}
		catch (UnknownHostException e) {
			throw new IllegalStateException(e);
		}
	}

	public static String getLocalHostName() {
		return getLocalHost().getHostName();
	}

	public static String getLocalHostAddress() {
		return getLocalHost().getHostAddress();
	}

	public static String getHostNameWithoutDomain(final InetAddress addr) {
		final String hostName = addr.getHostName();
		final int pos = hostName.indexOf('.');
		if (pos == -1) {
			return hostName;
		}
		return hostName.substring(0, pos);
	}

	public static int getAvailablePort() {
		try {
			ServerSocket s = new ServerSocket(0);
			s.setReuseAddress(true);
			s.close();
			return s.getLocalPort();
		}
		catch (IOException e) {
			throw new IllegalStateException("Failed to find an available port", e);
		}
	}

	public static int getAvialablePort(final int basePort) {
		if (basePort == 0) { return getAvailablePort(); }
		if (basePort < 0 || basePort > 65535) { throw new IllegalArgumentException("Illegal port number: " + basePort); }
		for (int i = basePort; i <= 65535; i++) {
			if (isPortAvailable(i)) { return i; }
		}
		throw new NoSuchElementException("Could not find available port greater than or equals to " + basePort);
	}

	public static boolean isPortAvailable(final int port) {
		ServerSocket s = null;
		try {
			s = new ServerSocket(port);
			s.setReuseAddress(true);
			return true;
		}
		catch (IOException e) {
			return false;
		}
		finally {
			if (s != null) {
				try {
					s.close();
				}
				catch (IOException e) {
				}
			}
		}
	}

	public static URI toURI(final URL url) {
		try {
			return url.toURI();
		}
		catch (URISyntaxException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	/**
	 * 产生符合URL规范的查询参数String ---- <code>foo=111&bar=222</code>
	 * 
	 * @param queries
	 *          查询参数映射 [name => value]
	 * @return 符合URL规范的查询参数String
	 */
	public static String geneHTTPQueryString(Map<String, String> queries) {
		StringBuilder sb = new StringBuilder();
		try {
			for (String key : queries.keySet()) {
				sb.append(key);
				sb.append('=');
				sb.append(URLEncoder.encode(queries.get(key), "iso-8859-1"));
				sb.append('&');
			}
		}
		catch (Exception e) {}
		
		return sb.deleteCharAt(sb.length() - 1).toString();
	}
	
}
